package com.powernode.ssm.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class RabbitMQStatusMonitor {

    @Autowired(required = false) // 避免在没有 rabbit 依赖时报错
    private ConnectionFactory connectionFactory;

    // 动态状态：是否 MQ 可用（可动态切换）
    private volatile boolean mqAvailable = false;

    public static boolean isMqAvailable() {
        return getInstance().mqAvailable;
    }

    // 单例模式获取当前实例（简化全局访问，也可用 Spring Bean 注入方式）
    private static RabbitMQStatusMonitor instance;

    public static RabbitMQStatusMonitor getInstance() {
        return instance;
    }

    @PostConstruct
    public void init() {
        instance = this;
        log.info("🟡 RabbitMQ状态监控组件已初始化，开始检测 MQ 连接状态...");
        checkMqStatus(); // 启动时立即检测一次
    }

    // 每隔 10 秒检测一次 RabbitMQ 是否还能连接
    @Scheduled(fixedRate = 10000) // 10秒检测一次，可根据需求调整
    public void checkMqStatus() {
        if (connectionFactory == null) {
            log.warn("🔴 RabbitMQ 未配置 ConnectionFactory，MQ 功能将被屏蔽");
            mqAvailable = false;
            return;
        }

        try {
            Connection connection = connectionFactory.createConnection();
            if (connection != null && connection.isOpen()) {
                if (!mqAvailable) {
                    log.info("✅ RabbitMQ 服务已恢复，邮件或消息等通讯功能将重新启用");
                    mqAvailable = true;
                }
                connection.close();
            } else {
                if (mqAvailable) {
                    log.warn("⚠️ RabbitMQ 连接已断开，将屏蔽邮件或消息等通讯功能");
                    mqAvailable = false;
                }
            }
        } catch (Exception e) {
            if (mqAvailable) {
                log.error("❌ RabbitMQ 连接检测失败，服务可能已宕机或网络中断，将屏蔽邮件或消息等通讯功能。原因：", e);
                mqAvailable = false;
            }
        }
    }
}